
package org.amos.upms.modules.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.amos.core.basic.utils.AmosUtils;
import org.amos.upms.modules.system.entity.Role;
import org.amos.upms.modules.system.entity.UserRole;
import org.amos.upms.modules.system.mapper.UserRoleMapper;
import org.amos.upms.modules.system.service.IRoleService;
import org.amos.upms.modules.system.service.IUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 用户角色关联 服务实现类
 *
 * @author CodeGenerator
 * @since 2020-12-20
 */
@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements IUserRoleService {
    @Autowired
    private IRoleService roleService;

    @Override
    public Set<Role> findRolesByUserId(Long userId) {
        Set<Long> roleIds = this.findRoleIdsByUserId(userId);
        if (CollUtil.isEmpty(roleIds)) {
            return new HashSet<>();
        }
        QueryWrapper<Role> qw = new QueryWrapper();
        qw.in(AmosUtils.toDbField(Role::getId), roleIds);
        Set<Role> roleSet = roleService.list(qw).stream().collect(Collectors.toSet());
        return roleSet;
    }

    @Override
    public Set<Long> findRoleIdsByUserId(Long userId) {
        QueryWrapper<UserRole> qw = new QueryWrapper<>();
        qw.eq(AmosUtils.toDbField(UserRole::getUserId), userId);
        List<UserRole> roles = super.list(qw);
        Set<Long> resultRoles = roles.stream().map(UserRole::getRoleId).collect(Collectors.toSet());
        return resultRoles;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateUserRole(Long userId, Set<Long> roleIds) {
        if (CollUtil.isNotEmpty(roleIds)) {
            //删除用户角色
            this.removeByUserIds(Collections.singleton(userId));
            //批量添加用户角色
            int res = baseMapper.addBatchRoles(userId, roleIds);
            return res > 0;
        }
        return Boolean.FALSE;
    }

    @Override
    public Boolean removeByUserIds(Set<Long> userIds) {
        UpdateWrapper<UserRole> uw = new UpdateWrapper<>();
        uw.in(AmosUtils.toDbField(UserRole::getUserId), userIds);
        return super.remove(uw);
    }
}
